#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from pathlib import Path
from PySide6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
    QLineEdit, QLabel, QTableWidget, QTableWidgetItem, QHeaderView,
    QFileDialog, QMessageBox, QProgressBar, QFrame, QSplitter, 
    QTabWidget, QApplication, QStyle
)
from PySide6.QtCore import Qt, QThreadPool, Signal, QObject, Slot, QRunnable, QSize
from PySide6.QtGui import QIcon, QFont, QColor, QPalette, QPixmap

from .task_manager import TaskManager
from .download_task import DownloadStatus


class PathInitializer(QRunnable):
    """路径初始化器，在后台线程中创建默认下载目录"""
    
    def __init__(self, callback):
        super().__init__()
        self.callback = callback
    
    def run(self):
        """在后台线程中执行路径初始化"""
        home_dir = str(Path.home())
        download_dir = os.path.join(home_dir, "Downloads")
        
        # 确保下载目录存在
        if not os.path.exists(download_dir):
            # 如果Downloads不存在，尝试本地化名称（如中文系统中可能是"下载"）
            download_dir = os.path.join(home_dir, "下载")
            if not os.path.exists(download_dir):
                # 如果仍不存在，使用用户目录
                download_dir = home_dir
        
        # 创建m3u8downloader子目录
        m3u8_download_dir = os.path.join(download_dir, "m3u8downloader")
        os.makedirs(m3u8_download_dir, exist_ok=True)
        
        # 回调通知主线程
        self.callback(m3u8_download_dir)


class CustomProgressBar(QProgressBar):
    """自定义进度条"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
            QProgressBar {
                border: 1px solid #CCCCCC;
                border-radius: 5px;
                text-align: center;
                height: 18px;
                margin: 2px;
                background: #F0F0F0;
            }
            QProgressBar::chunk {
                background-color: #4CAF50;
                border-radius: 5px;
            }
        """)


class DownloadSignals(QObject):
    """下载信号类，用于在线程间通信"""
    progress_updated = Signal(str, int)  # 任务ID, 进度
    status_updated = Signal(str, int)  # 任务ID, 状态枚举值
    task_completed = Signal(str)  # 任务ID
    task_failed = Signal(str, str)  # 任务ID, 错误信息
    path_initialized = Signal(str)  # 初始化完成的路径


class MainWindow(QMainWindow):
    """m3u8下载器主窗口"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("M3U8多任务下载器")
        self.resize(900, 700)
        
        # 设置应用样式
        self.setup_style()
        
        # 初始化线程池
        self.thread_pool = QThreadPool.globalInstance()
        
        # 初始化信号
        self.signals = DownloadSignals()
        self.signals.path_initialized.connect(self.on_path_initialized)
        
        # 初始化任务管理器
        self.task_manager = TaskManager(max_concurrent=10)
        self.task_manager.set_signals(self.signals)
        
        # 连接信号
        self.signals.progress_updated.connect(self.update_task_progress)
        self.signals.status_updated.connect(self.update_task_status)
        self.signals.task_completed.connect(self.on_task_completed)
        self.signals.task_failed.connect(self.on_task_failed)
        
        # 暂时设置默认路径为空，等待异步初始化
        self.default_download_path = ""
        
        # 设置UI
        self.setup_ui()
        
        # 异步初始化默认下载路径
        self.initialize_default_path()
    
    def setup_style(self):
        """设置应用样式"""
        # 设置全局样式表
        QApplication.setStyle("Fusion")
        
        # 设置应用程序样式表
        self.setStyleSheet("""
            QMainWindow {
                background-color: #F5F5F5;
            }
            QWidget {
                font-family: "微软雅黑", "Microsoft YaHei", "苹方", "PingFang SC", sans-serif;
                font-size: 14px;
            }
            QLineEdit {
                border: 1px solid #CCCCCC;
                border-radius: 5px;
                padding: 6px;
                background-color: white;
                selection-background-color: #007BFF;
            }
            QLineEdit:focus {
                border: 1px solid #007BFF;
            }
            QPushButton {
                background-color: #007BFF;
                color: white;
                border: none;
                border-radius: 5px;
                padding: 6px 12px;
                min-height: 30px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #0069D9;
            }
            QPushButton:pressed {
                background-color: #0062CC;
            }
            QTableWidget {
                border: 1px solid #DDDDDD;
                border-radius: 5px;
                background-color: white;
                gridline-color: #EEEEEE;
                selection-background-color: #E3F2FD;
                selection-color: #000000;
            }
            QHeaderView::section {
                background-color: #F8F9FA;
                border: 1px solid #DDDDDD;
                padding: 5px;
                font-weight: bold;
            }
            QScrollBar:vertical {
                border: none;
                background: #F0F0F0;
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: #BBBBBB;
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: #999999;
            }
            QTableWidget QTableCornerButton::section {
                background-color: #F8F9FA;
                border: 1px solid #DDDDDD;
            }
            QFrame#taskFrame {
                background-color: white;
                border-radius: 10px;
                border: 1px solid #DDDDDD;
            }
        """)
    
    def initialize_default_path(self):
        """异步初始化默认下载路径"""
        path_initializer = PathInitializer(self.signals.path_initialized.emit)
        self.thread_pool.start(path_initializer)
    
    @Slot(str)
    def on_path_initialized(self, path):
        """路径初始化完成的回调"""
        self.default_download_path = path
        self.save_path_input.setText(path)
        
    def setup_ui(self):
        """设置用户界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(15)
        
        # 创建任务框架
        task_frame = QFrame()
        task_frame.setObjectName("taskFrame")
        task_layout = QVBoxLayout(task_frame)
        task_layout.setContentsMargins(15, 15, 15, 15)
        task_layout.setSpacing(10)
        
        # 添加标题
        title_label = QLabel("M3U8 多任务下载管理器")
        title_label.setStyleSheet("font-size: 18px; font-weight: bold; color: #333333; margin-bottom: 10px;")
        title_label.setAlignment(Qt.AlignCenter)
        task_layout.addWidget(title_label)
        
        # 添加任务区域
        input_frame = QFrame()
        input_frame.setStyleSheet("background-color: #F8F9FA; border-radius: 5px; padding: 10px;")
        input_layout = QHBoxLayout(input_frame)
        input_layout.setContentsMargins(10, 10, 10, 10)
        input_layout.setSpacing(10)
        
        url_label = QLabel("M3U8链接:")
        input_layout.addWidget(url_label)
        
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入M3U8链接")
        input_layout.addWidget(self.url_input, 3)
        
        path_label = QLabel("保存路径:")
        input_layout.addWidget(path_label)
        
        self.save_path_input = QLineEdit()
        self.save_path_input.setPlaceholderText("保存路径初始化中...")
        self.save_path_input.setReadOnly(True)
        input_layout.addWidget(self.save_path_input, 2)
        
        self.browse_button = QPushButton("浏览")
        self.browse_button.setIcon(self.style().standardIcon(QStyle.SP_DirOpenIcon))
        self.browse_button.clicked.connect(self.browse_save_path)
        input_layout.addWidget(self.browse_button)
        
        self.add_task_button = QPushButton("添加任务")
        self.add_task_button.setIcon(self.style().standardIcon(QStyle.SP_FileDialogNewFolder))
        self.add_task_button.clicked.connect(self.add_task)
        self.add_task_button.setStyleSheet("""
            QPushButton {
                background-color: #28A745;
                color: white;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1E7E34;
            }
        """)
        input_layout.addWidget(self.add_task_button)
        
        task_layout.addWidget(input_frame)
        
        # 任务列表
        self.task_table = QTableWidget(0, 5)
        self.task_table.setHorizontalHeaderLabels(["URL", "保存路径", "状态", "进度", "操作"])
        self.task_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
        self.task_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.task_table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.task_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.task_table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        self.task_table.verticalHeader().setVisible(False)
        self.task_table.setAlternatingRowColors(True)
        self.task_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.task_table.setEditTriggers(QTableWidget.NoEditTriggers)
        
        task_layout.addWidget(self.task_table)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 10, 0, 0)
        button_layout.setSpacing(10)
        
        button_layout.addStretch()
        
        self.start_all_button = QPushButton("全部开始")
        self.start_all_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.start_all_button.clicked.connect(self.start_all_tasks)
        button_layout.addWidget(self.start_all_button)
        
        self.pause_all_button = QPushButton("全部暂停")
        self.pause_all_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        self.pause_all_button.clicked.connect(self.pause_all_tasks)
        self.pause_all_button.setStyleSheet("""
            QPushButton {
                background-color: #FFC107;
                color: white;
            }
            QPushButton:hover {
                background-color: #E0A800;
            }
            QPushButton:pressed {
                background-color: #D39E00;
            }
        """)
        button_layout.addWidget(self.pause_all_button)
        
        self.clear_completed_button = QPushButton("清除已完成")
        self.clear_completed_button.setIcon(self.style().standardIcon(QStyle.SP_DialogResetButton))
        self.clear_completed_button.clicked.connect(self.clear_completed_tasks)
        self.clear_completed_button.setStyleSheet("""
            QPushButton {
                background-color: #6C757D;
                color: white;
            }
            QPushButton:hover {
                background-color: #5A6268;
            }
            QPushButton:pressed {
                background-color: #545B62;
            }
        """)
        button_layout.addWidget(self.clear_completed_button)
        
        task_layout.addLayout(button_layout)
        
        main_layout.addWidget(task_frame)
        
        # 状态栏
        self.statusBar().setStyleSheet("background-color: #F8F9FA; color: #6C757D;")
        self.statusBar().showMessage("准备就绪")
    
    def browse_save_path(self):
        """浏览保存路径"""
        start_dir = self.default_download_path if self.default_download_path else str(Path.home())
        path = QFileDialog.getExistingDirectory(self, "选择保存目录", start_dir)
        if path:
            self.save_path_input.setText(path)
    
    def add_task(self):
        """添加下载任务"""
        url = self.url_input.text().strip()
        save_path = self.save_path_input.text().strip()
        
        if not url:
            QMessageBox.warning(self, "错误", "请输入M3U8链接")
            return
        
        if not save_path:
            if not self.default_download_path:
                QMessageBox.warning(self, "错误", "默认保存路径尚未初始化完成，请稍后再试或手动选择路径")
                return
            # 如果没有选择保存路径，使用默认路径
            save_path = self.default_download_path
            self.save_path_input.setText(save_path)
        
        # 添加到任务管理器
        task_id = self.task_manager.add_task(url, save_path)
        
        # 更新状态栏
        self.statusBar().showMessage(f"已添加新任务: {url}")
        
        # 添加到UI表格
        row = self.task_table.rowCount()
        self.task_table.insertRow(row)
        
        # 设置单元格内容
        url_item = QTableWidgetItem(url)
        url_item.setToolTip(url)  # 添加工具提示，方便查看长URL
        self.task_table.setItem(row, 0, url_item)
        
        path_item = QTableWidgetItem(save_path)
        path_item.setToolTip(save_path)  # 添加工具提示
        self.task_table.setItem(row, 1, path_item)
        
        status_item = QTableWidgetItem("等待中")
        status_item.setTextAlignment(Qt.AlignCenter)
        self.task_table.setItem(row, 2, status_item)
        
        # 自定义进度条
        progress_bar = CustomProgressBar()
        progress_bar.setRange(0, 100)
        progress_bar.setValue(0)
        self.task_table.setCellWidget(row, 3, progress_bar)
        
        # 操作按钮
        btn_frame = QFrame()
        btn_layout = QHBoxLayout(btn_frame)
        btn_layout.setContentsMargins(5, 0, 5, 0)
        btn_layout.setSpacing(5)
        
        # 开始按钮
        start_btn = QPushButton()
        start_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        start_btn.setToolTip("开始")
        start_btn.setFixedSize(28, 28)
        start_btn.clicked.connect(lambda: self.start_task(task_id))
        btn_layout.addWidget(start_btn)
        
        # 暂停按钮
        pause_btn = QPushButton()
        pause_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        pause_btn.setToolTip("暂停")
        pause_btn.setFixedSize(28, 28)
        pause_btn.setStyleSheet("""
            QPushButton {
                background-color: #FFC107;
                color: white;
            }
        """)
        pause_btn.clicked.connect(lambda: self.pause_task(task_id))
        btn_layout.addWidget(pause_btn)
        
        # 删除按钮
        delete_btn = QPushButton()
        delete_btn.setIcon(self.style().standardIcon(QStyle.SP_TrashIcon))
        delete_btn.setToolTip("删除")
        delete_btn.setFixedSize(28, 28)
        delete_btn.setStyleSheet("""
            QPushButton {
                background-color: #DC3545;
                color: white;
            }
        """)
        delete_btn.clicked.connect(lambda: self.delete_task(task_id, row))
        btn_layout.addWidget(delete_btn)
        
        self.task_table.setCellWidget(row, 4, btn_frame)
        
        # 存储任务ID (使用url_item已在前面创建的)
        url_item.setData(Qt.UserRole, task_id)
        
        # 自动开始任务
        self.task_manager.start_task(task_id)
        
        # 清空输入
        self.url_input.clear()
        self.url_input.setFocus()
    
    def find_row_by_task_id(self, task_id):
        """根据任务ID查找表格中的行"""
        for row in range(self.task_table.rowCount()):
            item = self.task_table.item(row, 0)
            if item and item.data(Qt.UserRole) == task_id:
                return row
        return -1
    
    @Slot(str, int)
    def update_task_progress(self, task_id, progress):
        """更新任务进度"""
        row = self.find_row_by_task_id(task_id)
        if row >= 0:
            progress_bar = self.task_table.cellWidget(row, 3)
            if progress_bar:
                progress_bar.setValue(progress)
                
                # 更新进度条颜色
                if progress < 30:
                    progress_bar.setStyleSheet("""
                        QProgressBar::chunk {
                            background-color: #007BFF;
                            border-radius: 5px;
                        }
                    """)
                elif progress < 70:
                    progress_bar.setStyleSheet("""
                        QProgressBar::chunk {
                            background-color: #17A2B8;
                            border-radius: 5px;
                        }
                    """)
                else:
                    progress_bar.setStyleSheet("""
                        QProgressBar::chunk {
                            background-color: #28A745;
                            border-radius: 5px;
                        }
                    """)
    
    @Slot(str, int)
    def update_task_status(self, task_id, status):
        """更新任务状态"""
        row = self.find_row_by_task_id(task_id)
        if row >= 0:
            status_text = "未知"
            color = QColor("#6C757D")  # 默认颜色
            
            if status == DownloadStatus.WAITING:
                status_text = "等待中"
                color = QColor("#6C757D")
            elif status == DownloadStatus.DOWNLOADING:
                status_text = "下载中"
                color = QColor("#007BFF")
            elif status == DownloadStatus.PAUSED:
                status_text = "已暂停"
                color = QColor("#FFC107")
            elif status == DownloadStatus.COMPLETED:
                status_text = "已完成"
                color = QColor("#28A745")
            elif status == DownloadStatus.FAILED:
                status_text = "失败"
                color = QColor("#DC3545")
            
            status_item = QTableWidgetItem(status_text)
            status_item.setTextAlignment(Qt.AlignCenter)
            status_item.setData(Qt.UserRole, status)
            status_item.setToolTip(status_text)
            self.task_table.setItem(row, 2, status_item)
            
            # 应用颜色
            self.task_table.item(row, 2).setForeground(color)
            
            # 更新状态栏
            if status == DownloadStatus.DOWNLOADING:
                self.statusBar().showMessage(f"正在下载: {self.task_table.item(row, 0).text()}")
    
    @Slot(str)
    def on_task_completed(self, task_id):
        """任务完成回调"""
        row = self.find_row_by_task_id(task_id)
        if row >= 0:
            status_item = QTableWidgetItem("已完成")
            status_item.setTextAlignment(Qt.AlignCenter)
            status_item.setData(Qt.UserRole, DownloadStatus.COMPLETED)
            status_item.setToolTip("已完成")
            self.task_table.setItem(row, 2, status_item)
            
            # 应用颜色
            self.task_table.item(row, 2).setForeground(QColor("#28A745"))
            
            progress_bar = self.task_table.cellWidget(row, 3)
            if progress_bar:
                progress_bar.setValue(100)
                progress_bar.setStyleSheet("""
                    QProgressBar::chunk {
                        background-color: #28A745;
                        border-radius: 5px;
                    }
                """)
            
            # 更新状态栏
            self.statusBar().showMessage(f"下载完成: {self.task_table.item(row, 0).text()}")
    
    @Slot(str, str)
    def on_task_failed(self, task_id, error_msg):
        """任务失败回调"""
        row = self.find_row_by_task_id(task_id)
        if row >= 0:
            status_item = QTableWidgetItem("失败")
            status_item.setTextAlignment(Qt.AlignCenter)
            status_item.setData(Qt.UserRole, DownloadStatus.FAILED)
            status_item.setToolTip(f"失败: {error_msg}")
            self.task_table.setItem(row, 2, status_item)
            
            # 应用颜色
            self.task_table.item(row, 2).setForeground(QColor("#DC3545"))
            
            # 更新状态栏
            self.statusBar().showMessage(f"下载失败: {error_msg}")
    
    def start_task(self, task_id):
        """开始指定任务"""
        self.task_manager.start_task(task_id)
        row = self.find_row_by_task_id(task_id)
        if row >= 0:
            self.statusBar().showMessage(f"开始任务: {self.task_table.item(row, 0).text()}")
    
    def pause_task(self, task_id):
        """暂停指定任务"""
        self.task_manager.pause_task(task_id)
        row = self.find_row_by_task_id(task_id)
        if row >= 0:
            self.statusBar().showMessage(f"暂停任务: {self.task_table.item(row, 0).text()}")
    
    def delete_task(self, task_id, row):
        """删除指定任务"""
        # 确认对话框
        reply = QMessageBox.question(
            self, "确认删除", 
            "是否确认删除此任务？", 
            QMessageBox.Yes | QMessageBox.No, 
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.task_manager.remove_task(task_id)
            # 找到最新的行号（因为可能已经改变）
            current_row = self.find_row_by_task_id(task_id)
            if current_row >= 0:
                self.task_table.removeRow(current_row)
            self.statusBar().showMessage("已删除任务")
    
    def start_all_tasks(self):
        """开始所有任务"""
        self.task_manager.start_all_tasks()
        self.statusBar().showMessage("已开始所有任务")
    
    def pause_all_tasks(self):
        """暂停所有任务"""
        self.task_manager.pause_all_tasks()
        self.statusBar().showMessage("已暂停所有任务")
    
    def clear_completed_tasks(self):
        """清除已完成的任务"""
        # 获取已完成任务的行
        completed_rows = []
        for row in range(self.task_table.rowCount()):
            status_item = self.task_table.item(row, 2)
            if status_item and status_item.text() == "已完成":
                task_id = self.task_table.item(row, 0).data(Qt.UserRole)
                self.task_manager.remove_task(task_id)
                completed_rows.append(row)
        
        # 从后往前删除行，避免索引改变
        for row in sorted(completed_rows, reverse=True):
            self.task_table.removeRow(row)
        
        if completed_rows:
            self.statusBar().showMessage(f"已清除 {len(completed_rows)} 个已完成的任务") 